const app = getApp()

const doLogin = () => {
  wx.login({
    success: loginRes => {
      console.log('wx.login success', loginRes);
      const pages = getCurrentPages()
      if (pages.length && pages[0].hasOwnProperty('getToken')) {
        pages[0].getToken({ token: 'aa', openId: 'bb' })
      }
      if (loginRes.code) {
        wx.request({
          url: 'https://bm.zhushui.net/tax/api/auth/session/openid',
          method: 'POST',
          header: {},
          data: {
            code: loginRes.code
          },
          success: res => {
            if (res.code === '10000') {
              const data = {
                token: res.token,
                openId: res.openId
              }
              this.globalData.userInfo = {...data}
              wx.setStorageSync('loginFlag', true)
              wx.setStorageSync('userInfo', JSON.stringify(data))
            }
          },
          fail: err => {
            wx.setStorageSync('loginFlag', false)
          }
        })
      }
    },
    fail: err => {
      console.log('wx.login fail');
    }
  })
}

const request = (url, options) => {
   return new Promise((resolve, reject) => {
       wx.request({
           url: `${app.globalData.host}${url}`,
           method: options.method,
           data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
           header: options.header,
           success(request) {
               if (request.data.status === true) {
                   resolve(request.data)
               } else if (request.statusCode === 401) {
                doLogin()
               } else {
                   reject(request)
               }
           },
           fail(error) {
               reject(error)
           }
       })
   })
}

const get = (url, data = {}, header = {}) => {
   return request(url, { method: 'GET', data, header })
}

const post = (url, data, header = {}) => {
   return request(url, { method: 'POST', data, header })
}

module.exports = {
  get,
  post
}
